﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections;

namespace 新蒙蔽机器人
{
    [Serializable]
    public class Packge : IPackge
    {
        public string name { get; set; }
        private string path;
        private List<VoiceItem> items = new List<VoiceItem>();

        public string getVoice(string gift_partten)
        {
            VoiceItem temp = null;
            string gift_name = Regex.Match(gift_partten, "赠送了(\\d)个([\\s\\S])").Groups[2].Value;
            temp = items.Find((s) => s.name.Equals(gift_partten));
            if (temp == null)
            {
                return "";
            }
            System.Windows.Forms.MessageBox.Show(temp.path, "有礼物");
            return temp.path;  
        }

        public bool setVoiceList(List<VoiceItem> e)
        {
            if (e == null)
            {
                return false;
            }
            items = e;
            return true;
        }
        public List<VoiceItem> getVoiceList()
        {
            return items;
        }
        public bool setVoiceToPackge()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 透过礼物名获取路径
        /// </summary>
        /// <returns></returns>
        public string getPath(string name)
        {
            VoiceItem vit = null;
            vit = items.Find((s) => s.name == name);
            if (vit==null || vit.status==0)//安全检查或可用性检测
            {
                return "";
            }
            return vit.path;
        }
        public void setPath(string path)
        {
            this.path = path;
        }
        /// <summary>
        /// 根据路径把内容包装起来放到路径中，调用前提是必须setPath();
        /// </summary>
        /// <returns></returns>
        public bool pack() { 
            string ttsc_path = AppDomain.CurrentDomain.BaseDirectory+"/Addons/ttsc";
            if (!Directory.Exists(ttsc_path))
            {
                Directory.CreateDirectory(ttsc_path);
            }
            if (!string.IsNullOrWhiteSpace(path))
            {
                //List<EachFileInfo> files = new List<EachFileInfo>();
                EachFileInfo files = new EachFileInfo();
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                using (Stream file_stream = new FileStream(path, FileMode.Create))
                {
                    BufferedStream buff = new BufferedStream(file_stream);
                    for (int i = 0; i < 8; i++)
                    {
                        buff.WriteByte(0);//腾出头8个字节的位置
                    }
                    buff.Flush();
                    foreach (VoiceItem item in getVoiceList())
                    {
                        /*文件处理*/
                        if (System.IO.File.Exists(item.path))
                        {
                            //获取文件的长度
                            byte[] bin = System.IO.File.ReadAllBytes(item.path);
                            files.list.Add(new EachFileInfo.Info { name = item.name, lenght = bin.GetLongLength(0), offset = buff.Position+1, path = item.path.Substring(item.path.LastIndexOf('\\')+1) });
                            buff.Write(bin, 0, bin.Length);
                            buff.Flush();
                            bin = null;
                        }
                    }
                    /*填充隔离带*/
                    for (int i = 0; i < 8; i++)
                    {
                        buff.WriteByte(0);
                    }
                    /*写入序列化对象的开始位置*/
                    byte[] tmpk = System.Text.ASCIIEncoding.ASCII.GetBytes((buff.Position).ToString());
                    buff.Seek(0, SeekOrigin.Begin);
                    buff.Write(tmpk, 0, tmpk.Length);
                    buff.Seek(buff.Length, SeekOrigin.Begin);
                    buff.Flush();
                    /*打包处理*/
                    Bina.Serialize<EachFileInfo>(files, file_stream);
                }
                return true;
            }
            return false;
        }
        /// <summary>
        /// 内置的解包方法，可以把包中的序列解析为本包的内容
        /// 如name、List<VoiceItem>
        /// </summary>
        /// <returns></returns>
        public bool unpack()
        {
            if (!string.IsNullOrWhiteSpace(path)&& File.Exists(path))
            {
                EachFileInfo files = new EachFileInfo();
                if (!Directory.Exists(plugin.BASEDIR))
                {
                    Directory.CreateDirectory(plugin.BASEDIR);
                }
                using (Stream fsr = new FileStream(path, FileMode.Open))
                {
                    BufferedStream buff = new BufferedStream(fsr);
                    byte[] btts;
                    
                    /*获取对象位置*/
                    btts = new byte[8];//首读4个字节获取对象的开始位置
                    buff.Read(btts, 0, btts.Length);
                    string obj_offset_str = System.Text.ASCIIEncoding.ASCII.GetString(btts);
                    long obj_offset_position = int.Parse(obj_offset_str);
                    buff.Seek(obj_offset_position, SeekOrigin.Begin);//设置位置到对象的起始位置
                    /*获取对象*/
                    using (MemoryStream tmpstr =new MemoryStream())
                    {
                        long obj_length = buff.Length - buff.Position;
                        while (obj_length>0)
                        {
                            byte[] btmp = new byte[2];
                            int n= buff.Read(btmp, 0, btmp.Length);
                            if (n == 0)
                                break;
                            tmpstr.Write(btmp, 0, btmp.Length);
                            obj_length -= n;
                        }
                        tmpstr.Flush();
                        tmpstr.Seek(0, SeekOrigin.Begin);
                        files = Bina.DeSerialize<EachFileInfo>(tmpstr);//反序列化对象
                    }
                    if (files == null)
                        return false;
                    /*解析对象*/
                    
                    foreach (EachFileInfo.Info item in files.list)
                    {
                        buff.Seek(item.offset, SeekOrigin.Begin);
                        using (Stream newfile = new FileStream(plugin.BASEDIR + item.path, FileMode.OpenOrCreate))
                        {
                            BufferedStream tempnewfile = new BufferedStream(newfile);
                            while (buff.Position < item.lenght)
                            {
                                btts = new byte[256];
                                int n = buff.Read(btts, 0, btts.Length);
                                tempnewfile.Write(btts, 0, n);
                                tempnewfile.Flush();
                            }
                        }
                        items.Add(new VoiceItem { name = item.name, path = plugin.BASEDIR + item.path, tag = item.path, status = 1 });//应用到包
                    }
                    buff.Close();
                }
            }
            return true;
        }
    }
  
    public class VoiceItem
    {
        public string name { get; set; }
        public string tag { get; set; }
        public string path { get; set; }
        public int status { get; set; }
    }
}
